package com.zys.sac.core.handler;

import com.zys.sac.core.constant.RequestParam;
import com.zys.sac.core.constant.RequestStatus;
import com.zys.sac.core.helper.TokenManager;
import com.zys.sac.core.util.ServletResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zhongjunkai on 2022/4/14.
 */
@Slf4j
public class SacLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private TokenManager tokenManager;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        //将token从缓存中移除
        String token = request.getHeader(RequestParam.TOKEN);
        if (!StringUtils.hasText(token)) {
            ServletResponseUtils.render(response, ServletResponseUtils.result(RequestStatus.INVALIDTOKEN.getCode(), RequestStatus.INVALIDTOKEN.getMsg()));
            return;
        }
        try {
            tokenManager.invalidToken(token);
        } catch (Exception e) {
            log.error("删除缓存发生异常：{}", e);
            ServletResponseUtils.render(response, ServletResponseUtils.result(RequestStatus.INVALIDTOKEN.getCode(), RequestStatus.INVALIDTOKEN.getMsg()));
            return;
        }
        doOtherThings();
        ServletResponseUtils.render(response, ServletResponseUtils.result(RequestStatus.LOGOUTSUCCESS.getCode(), RequestStatus.LOGOUTSUCCESS.getMsg()));
    }

    /**
     * 补充函数，在登出时，如果还有其他逻辑需要处理，可以集成该接口并覆盖本方法，在使用时，只需要集成本接口并实例化成spring bean会自动覆盖默认提供的bean
     */
    public void doOtherThings() {
        //do nothing，you can do anything you would
    }
}
